package cn.edu.ctbu.datajpa3.service;

import cn.edu.ctbu.datajpa3.entity.Student;
import cn.edu.ctbu.datajpa3.repository.StudentRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class StudentService {

    private final StudentRepository studentRepository;

    public StudentService(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    // 获取所有学生（支持分页）
    public Page<Student> findAll(Pageable pageable) {
        return studentRepository.findAll(pageable);
    }

    // 按姓名模糊查询学生
    public Page<Student> findByName(String name, Pageable pageable) {
        return studentRepository.findByNameContaining(name, pageable);
    }

    // 按学号模糊查询学生
    public Page<Student> findByStudentNumber(String studentNumber, Pageable pageable) {
        return studentRepository.findByStudentNumberContaining(studentNumber, pageable);
    }

    // 按姓名或学号模糊查询学生
    public Page<Student> findByNameOrStudentNumber(String name, String studentNumber, Pageable pageable) {
        // 如果没有提供查询条件，则返回所有学生
        if (name == null && studentNumber == null) {
            return studentRepository.findAll(pageable);
        }
        return studentRepository.findByNameContainingOrStudentNumberContaining(name, studentNumber, pageable);
    }

    // 根据 ID 获取学生信息
    public Optional<Student> findById(Integer id) {
        return studentRepository.findById(id);
    }

    // 保存学生信息（添加或更新）
    public void save(Student student) {
        studentRepository.save(student);
    }

    // 删除学生
    public void delete(Integer id) {
        studentRepository.deleteById(id);
    }
}